import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import { publicRoutes, privateRoutes } from './routes/index.jsx';
import { getUserInfo } from './services/auth';
import { BasicLayout } from './layouts';
import './App.css';

function App() {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // 检查用户登录状态
  useEffect(() => {
    checkLoginStatus();
  }, []);

  const checkLoginStatus = async () => {
    try {
      const userInfo = await getUserInfo();
      // 由于修改了getUserInfo函数，现在直接返回用户信息对象
      if (userInfo && userInfo.id) {
        setCurrentUser(userInfo);
      } else {
        setCurrentUser(null);
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
      setCurrentUser(null);
    } finally {
      setLoading(false);
    }
  };

  // 检查用户是否有权限访问特定路由
  const hasPermission = (route) => {
    // 如果路由没有指定权限要求，则所有登录用户都可以访问
    if (!route.access) {
      return true;
    }
    
    // 对于用户管理页面，只有管理员角色可以访问
    if (route.access === 'user:manage') {
      // 检查用户是否有admin角色
      return currentUser?.roles?.includes('admin') || false;
    }
    
    // 其他路由默认允许访问
    return true;
  };

  // 渲染私有路由内容
  const renderPrivateRoute = ({ element: Element, access, ...rest }) => {
    // 检查用户是否有权限访问此路由
    if (access && !hasPermission({ access })) {
      return (
        <BasicLayout currentUser={currentUser}>
          <div className="no-permission">
            <h2>无访问权限</h2>
            <p>您没有权限访问此页面，请联系管理员获取权限。</p>
          </div>
        </BasicLayout>
      );
    }
    
    return (
      <BasicLayout currentUser={currentUser}>
        <Element {...rest} />
      </BasicLayout>
    );
  };

  if (loading) {
    return <div className="loading-container">加载中...</div>;
  }

  return (
    <ConfigProvider locale={zhCN}>
      <Router>
        <Routes>
          {/* 公共路由 */}
          {publicRoutes.map((route) => (
            <Route
              key={route.path}
              path={route.path}
              element={route.element}
            />
          ))}
          
          {/* 私有路由 */}
          {privateRoutes.map((route) => (
            <Route
              key={route.path}
              path={route.path}
              element={
                currentUser ? (
                  renderPrivateRoute(route)
                ) : (
                  <Navigate to="/login" replace />
                )
              }
            />
          ))}
          
          {/* 未匹配的路由重定向到登录页 */}
          <Route path="*" element={<Navigate to="/login" replace />} />
        </Routes>
      </Router>
    </ConfigProvider>
  );
}

export default App;
